﻿package com.alstudio.ui.module.user;

import java.io.File;
import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.module.xmpp.protocol.xmpp.data.ALPhoto;
import com.alstudio.module.xmpp.request.ALUiXmppRequestCreator;
import com.alstudio.pojo.ALXmppEvent;
import com.alstudio.pojo.module.user.User;
import com.alstudio.ui.base.TitleBarActivity;
import com.alstudio.ui.module.image.browser.LargerPhotoActivity;
import com.alstudio.utils.android.net.http.UploadPhotoRequest;
import com.alstudio.utils.log.ALLog;
import com.alstudio.view.absadapter.PhotoAdapter;
import com.loovee.imaohu.R;

/**
 * @ClassName: PhotoActivity
 * @Description: 相册管理
 * @author 邓亚辉
 * @date 2014-03-26
 */
public class PhotoActivity extends TitleBarActivity {

	// 显示的是否是我的个人头像
	private boolean isMyIcons = true;

	private ArrayList<ALPhoto> photos = new ArrayList<ALPhoto>();
	// 此对象用于暂存待上传的头像。上传成功后再传递到我的vcard中
	private ALPhoto tempPhoto;
	private User mUser;
	private GridView gridView;
	private PhotoAdapter adapter;

	// add by alonso lee 此标志位用于V认证选择图片
	private boolean selectMyPhoto = false;

	public Handler mhandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			adapter.notifyDataSetChanged();
		};
	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.TitleBarActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setupView(this, getClass().getSimpleName());
		initData();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#setupView(android.content.Context,
	 * java.lang.String)
	 */
	@Override
	protected void setupView(Context context, String name) {
		super.setupView(context, name);
		setTitleBarActivityContentView(R.layout.photo_layout);
		setCenterTextViewMessage(R.string.TxtMyPhotoList);
		rightUseImageButton(true);
		setRightButtonImageSrc(R.drawable.albums_icon_add);
		// setRightButtonBackground(R.drawable.albums_icon_add);
		// setRightButtonClickListener(this);
		// setViewOnclickListener(R.id.button_left, this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#initData()
	 */
	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		// add by alonso lee 此标志位用于V认证选择图片
		selectMyPhoto = getIntent().getBooleanExtra("selectMyPhoto", false);
		mUser = (User) getIntent().getSerializableExtra("user");
		// add by alonso lee
		if (mUser == null) {
			mUser = ALLocalEnv.getLocalEnv().getMyProfile();
		}
		if (ALLocalEnv.getBareJid(mUser.getJid()).equals(
				ALLocalEnv.getLocalEnv().getMyAccount().getUserName())) {
			ALLog.d("查看自己的主頁");
			isMyIcons = true;
			// photos.addAll(mUser.getPhotos());
		} else {
			isMyIcons = false;
			// photos.addAll(mUser.getPhotos());
		}
		// photos = mUser.getPhotos();
		photos.addAll(mUser.getPhotos());

		int vPos = mUser.getvAuthPos();
		if (vPos != -1 && vPos < photos.size()) {
			ALPhoto p = photos.get(vPos);
			p.setVauth(true);
		}

		initUI();
	}

	private void initUI() {
		setTitle();
		initGridView();
	}

	private void initGridView() {
		gridView = (GridView) findViewById(R.id.gridview);
		adapter = new PhotoAdapter(photos, isMyIcons, (mUser.getVauthed() == 1));
		gridView.setAdapter(adapter);
		gridView.setOnItemClickListener(onItemClickListener);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onRestart()
	 */
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		if (isMyIcons) {
			// photos = mUser.getPhotos();
			photos.clear();
			photos.addAll(ALLocalEnv.getLocalEnv().getMyProfile().getPhotos());
			adapter.setVauth(ALLocalEnv.getLocalEnv().getMyProfile()
					.getVauthed() == 1);
			ALLog.d(" 图片张数 " + photos.size());
			adapter.notifyDataSetChanged();
		}
	}

	/**
	 * 设置相册标题
	 */
	private void setTitle() {
		if (isMyIcons) {
			setCenterTextViewMessage(R.string.TxtMyPhotoList);
		} else {
			// 好友的相册
			goneView(R.id.button_right);
			if (mUser.getSex().equals("male")) {
				setCenterTextViewMessage(R.string.TxtFriendPhotoListSuffix1);
			} else {
				setCenterTextViewMessage(R.string.TxtFriendPhotoListSuffix2);
			}
		}
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.TitleBarActivity#invokeRightBtnClick()
	 */
	@Override
	protected void invokeRightBtnClick() {
		// TODO Auto-generated method stub
		super.invokeRightBtnClick();
		if (isMyIcons) {
			showPhotoProcessDialog();
		}
	}

	private void saveMyPhotos() {
		if (!ALLocalEnv.isSendXmppDataEnable()) {
			return;
		}
		showLoadingProgress();
		User u = new User();
		u.getPhotos().addAll(photos);
		ALUiXmppRequestCreator.postALUiXmppModifyUserProfileEvent(u);
	}

	/**
	 * 网格布局的子项点击事件监听
	 */
	private OnItemClickListener onItemClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// modify by alonso lee 此标志位用于V认证选择图片
			if (isMyIcons && !selectMyPhoto) {// 查看自己相册
				viewLargePic(position, photos);
			} else {
				// modify by alonso lee V认证选择照片，设置返回参数后直接关闭界面
				Intent i = new Intent();
				i.putExtra("postion", position + "");
				i.putExtra("fileid", photos.get(position).getThumbnailFileid());
				setResult(RESULT_OK, i);
				finish();
			}
		}
	};

	/**
	 * 查看大图
	 * 
	 * @param position
	 * @param photos
	 */
	private void viewLargePic(int position, ArrayList<ALPhoto> photos) {

		Intent intent = new Intent(this, LargerPhotoActivity.class);
		intent.putExtra("index", position);
		intent.putExtra("photos", photos);
		intent.putExtra("isMyIcon", isMyIcons);
		intent.putExtra("vPos", mUser.getvAuthPos());
		startActivity(intent);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.TitleBarActivity#onGetProcessPhotosResult(java.lang
	 * .String, java.lang.String)
	 */
	@Override
	protected void onGetProcessPhotosResult(String path, String name) {
		// TODO Auto-generated method stub
		super.onGetProcessPhotosResult(path, name);
		Uri uri = Uri.fromFile(new File(path));
		ALLog.d("得到图片路径" + uri.toString());
		// 上传图片
		uploadPic(path);
		showLoadingProgress();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.TitleBarActivity#handleUploadPicSuccess(com.alstudio
	 * .utils.android.net.http.UploadPhotoRequest, java.lang.String,
	 * java.lang.String)
	 */
	@Override
	protected void handleUploadPicSuccess(UploadPhotoRequest sender,
			String pictureFileId, String thumbFileId) {
		// TODO Auto-generated method stub
		super.handleUploadPicSuccess(sender, pictureFileId, thumbFileId);
		dismissLoadingProgress();
		ALLog.d("图片上传成功 " + pictureFileId + "小兔 " + thumbFileId);
		tempPhoto = new ALPhoto();
		tempPhoto.setPicFileid(pictureFileId);
		tempPhoto.setThumbnailFileid(thumbFileId);
		ALLocalEnv.getLocalEnv().getMyProfile().getPhotos().add(tempPhoto);
		photos.clear();
		photos.addAll(ALLocalEnv.getLocalEnv().getMyProfile().getPhotos());
		// photos = ALLocalEnv.getLocalEnv().getMyProfile().getPhotos();
		// adapter.notifyDataSetChanged();
		mhandler.sendEmptyMessage(1);

		saveMyPhotos();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleModifyUserProfileEvent(com.alstudio
	 * .pojo.ALXmppEvent)
	 */
	@Override
	public void handleModifyUserProfileEvent(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleModifyUserProfileEvent(data);
		if (data.getResponseCode() == ALXmppEvent.RESPONSE_OK) {
			ALLog.d("修改资料成功");
			mhandler.sendEmptyMessage(1);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#finish()
	 */
	@Override
	public void finish() {
		mhandler.removeMessages(1);
		super.finish();
	}

}
